# -*- coding:utf-8 -*-
from flask import Flask, render_template, url_for, request, redirect, make_response, session, g, send_from_directory
import os
import pymysql
from functools import wraps
# from keyword import WC
from werkzeug.utils import secure_filename
import keywords
import MainIdea
import json

from sendEmail import sendEmail
import random

db = pymysql.connect(host="localhost", user="root", password="1234", database="texta")
app = Flask(__name__)
app.config['SECRET_KEY'] = '1234'
# app.config['UPLOAD_FOLDER'] = "E:/OnlineTextAnalyse/files/"
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'doc', 'docx', 'png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])
cur = db.cursor()


# 统计文本词频、绘制词云图
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if hasattr(g, 'UserName'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))

    return wrapper


# 定义首页路由
@app.route("/", methods=['GET', "POST"])
def index():
    if request.method == 'GET':
        session.clear()
        return render_template('index.html')


# 定义登录页面路由
@app.route("/login/", methods=['GET', "POST"])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        UserEmail = str(request.form.get("UserEmail"))
        session["UserEmail"] = UserEmail
        UserPassWord = str(request.form.get("UserPassWord"))
        # sql = "select UserPassWord from user where UserEmail = %s" %(UserEmail)
        cur.execute("select UserPassWord from userinfo where UserEmail = %s", (UserEmail))
        UserIn = cur.fetchall()
        cur.execute("select * from userinfo where UserEmail = %s", (UserEmail))
        UserId = cur.fetchone()[0]
        print(UserId)
        if len(UserIn) != 0:
            if UserIn[0][0] == UserPassWord:
                session["UserEmail"] = UserEmail
                session["UserPassWord"] = UserPassWord
                session['UserId'] = UserId
                return redirect(url_for("wbfx", UserEmail=UserEmail))
            else:
                return u'密码错误，请查证后登录！'
        else:
            return "邮箱错误，请查证后登录！"


# 定义注销页面路由,或者在HTML中添加按钮，然后返回登录界面
@app.route('/logout/', methods=['GRT', 'POST'])
def logout():
    session.clear()
    return redirect(url_for('index'))


# 定义注册页面
@app.route('/regist/', methods=['GET', 'POST'])
def regist():
    if request.method == "GET":
        return render_template('regist.html')
    else:
        UserName = str(request.form.get('UserName'))
        UserEmail = str(request.form.get('UserEmail'))
        UserPassWord1 = str(request.form.get('UserPassWord1'))
        UserPassWord2 = str(request.form.get('UserPassWord2'))
        cur.execute('select UserEmail from userinfo where UserEmail = %s', (UserEmail))
        UserRe = cur.fetchall()
        if len(UserRe) != 0:
            return u'邮箱已经注册过！'
        else:
            if UserPassWord1 != UserPassWord2 or len(UserPassWord1) == 0:
                return u'两次密码不一致1'
            else:
                cur.execute('insert into userinfo(UserName,UserEmail,UserPassWord) values(%s,%s,%s)',
                            (UserName, UserEmail, UserPassWord1))
                db.commit()
                return redirect(url_for('login'))


# 定义登录后主界面
@app.route('/wbfx/', methods=['GET', 'POST'])
def wbfx():
    if request.method == "GET":
        UserEmail = session["UserEmail"]
        cur.execute("select UserID from userinfo where UserEmail = %s ", (UserEmail))
        UserID = cur.fetchone()[0]
        print(UserID)
        cur.execute("select * from analysisresult where UserID = %s limit 6", (UserID))
        results = cur.fetchall()
        photos = []
        ProjectID = []
        for i in range(len(results)):
            photos.append(results[i][2])
            ProjectID.append(results[i][1])
        print(photos)
        print(ProjectID)
        base_path = os.path.abspath(os.path.dirname(__file__))
        wordcloudStreams = []
        for photo in photos:
            wordcloudStreams.append(return_img_stream(base_path + photo))

        return render_template('wbfx.html', wordcloudStreams=wordcloudStreams, ProjectID=ProjectID)


# 定义我的文件界面
@app.route('/myfile/', methods=['GET', 'POST'])
def myfile():
    if request.method == "GET":
        UserEmail = session["UserEmail"]
        cur.execute("select UserID from userinfo where UserEmail = %s ", (UserEmail))
        UserID = cur.fetchone()[0]
        print(UserID)
        cur.execute("select * from analysisresult where UserID = %s limit 6", (UserID))
        results = cur.fetchall()
        photos = []
        ProjectID = []
        for i in range(len(results)):
            photos.append(results[i][2])
            ProjectID.append(results[i][1])
        print(photos)
        print(ProjectID)
        base_path = os.path.abspath(os.path.dirname(__file__))
        wordcloudStreams = []
        for photo in photos:
            wordcloudStreams.append(return_img_stream(base_path + photo))

        return render_template('wbfx.html', wordcloudStreams=wordcloudStreams, ProjectID=ProjectID)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 定义尝试界面
@app.route('/justtry/', methods=['GET', 'POST'])
def justtry():
    return render_template('justtry.html')


def return_img_stream(img_local_path):
    import base64
    img_stream = ""
    with open(img_local_path, "rb") as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream).decode()
        # img_stream = base64.b64encode(img_stream)
    return img_stream


# 定义新建分析页面
@app.route('/new/', methods=['GET', 'POST'])
def new():
    if request.method == "GET":
        return render_template('new.html')
    else:
        if request.form.get('AnalyseText'):
            AnalyseText = request.form.get('AnalyseText').encode('utf-8')
        elif request.files['file1']:
            file1 = request.files['file1']
            file1name = secure_filename(file1.filename)
            base_path = os.path.abspath(os.path.dirname(__file__))
            upload_path = os.path.join(base_path, 'static/upload/', file1name)
            file1.save(upload_path)

            # AnalyseText = open("E:/OnlineTextAnalyse/files/" + file1name,"rb").read()
            def get_file_content(path):
                with open(path, 'rb') as fp:
                    return fp.read()

            AnalyseText = get_file_content(upload_path)
        else:
            return render_template('new.html')
        if len(AnalyseText) != 0:
            session["AnalyseText"] = AnalyseText.decode('utf-8')
            return redirect(url_for('AnalyseResult'))


# 定义分析结果页面
@app.route('/AnalyseResult/', methods=['GET', 'POST'])
def AnalyseResult():
    base_path = os.path.abspath(os.path.dirname(__file__))
    if request.method == "GET":
        UserEmail = session["UserEmail"]
        AnalyseText = session.get("AnalyseText")
        cur.execute('select UserID from userinfo where UserEmail = %s', (UserEmail))
        UserID = cur.fetchall()[0][0]
        cur.execute('select ProjectID from analysisresult where UserID = %s', (UserID))
        UserProjectNum = len(cur.fetchall())
        ProjectID = str(UserID) + "_" + str(UserProjectNum + 1)
        session["ProjectID"] = ProjectID
        font = "simhei.ttf"
        shape = base_path + "/static/images/rectangle.bmp"
        maxwords = 200
        wt = keywords.keyword(AnalyseText, maxwords, ProjectID)
        highwordsfilePath = wt[1]
        session["highwordsfilePath"] = highwordsfilePath
        session["wt0"] = wt[0]
        wt0 = wt[0]
        wtpath = base_path + "/static/userwt/" + str(ProjectID) + ".txt"
        print(wtpath)
        with open(wtpath, "w", encoding="utf-8") as f:
            f.write(wt0)

        wordcloudPath = keywords.WC(wt0, font, shape, maxwords, ProjectID)
        wordcloudStream = return_img_stream(wordcloudPath)
        Asummary = MainIdea.summary(AnalyseText)
        session["Asummary"] = Asummary
        summaryfilepath = base_path + "/static/summary/" + str(ProjectID) + ".txt"
        session["summaryfilepath"] = summaryfilepath
        with open(summaryfilepath, "w", encoding="utf-8") as f:
            f.write(Asummary)
        # 将结果插入到数据库
        cloud_re_path = wordcloudPath.replace(base_path, '')
        high_re_path = highwordsfilePath.replace(base_path, '')
        summary_re_path = summaryfilepath.replace(base_path, '')
        cur.execute('insert into analysisresult(UserID,ProjectID,Photo,HighFreq,MainIdea) values(%s,%s,%s,%s,%s)',
                    (UserID, ProjectID, cloud_re_path, high_re_path, summary_re_path))
        db.commit()
        # return render_template('AnalyseResult.html', wordcloudStream = wordcloudStream, ProjectID = ProjectID, wt = wt)
        return render_template('AnalyseResult.html', wordcloudStream=wordcloudStream, Asummary=Asummary,
                               wordcloud=str(ProjectID) + ".jpg", highwords=str(ProjectID) + '.txt',
                               summary=str(ProjectID) + '.txt')
    else:
        ProjectID = session.get("ProjectID")
        wt0 = session.get("wt0")
        Asummary = session.get("Asummary")
        highwordsfilePath = session.get("highwordsfilePath")
        summaryfilepath = session.get("summaryfilepath")
        AnalyseText = session.get("AnalyseText")

        font = request.values.get("font")
        if font == "heiti":
            font = "simhei.ttf"
        else:
            font = base_path + "/static/font/" + font + ".ttf"

        shape = request.values.get("shape")
        if shape == "map":
            shape = base_path + "/static/images/dingding.bmp"
        else:
            shape = base_path + "/static/images/" + shape + '.bmp'

        if request.files['file2']:
            imag = request.files['file2']
            imagname = secure_filename(imag.filename)
            upload_image_path = base_path + '/static/user_images/' + imagname
            imag.save(upload_image_path)
            shape = upload_image_path

        maxwords = request.values.get("maxwords")
        maxwords = int(maxwords)
        wordcloudPath = keywords.WC(wt0, font, shape, maxwords, ProjectID)
        wordcloudStream = return_img_stream(wordcloudPath)
        cur.execute('select max(times) from photostyle where ProjectID = %s', (ProjectID))
        maxtimes = cur.fetchall()[0][0]
        if maxtimes != None:
            cur.execute('insert into photostyle(ProjectID,times,font,shape,maxwords) values(%s,%s,%s,%s,%s)',
                        (ProjectID, maxtimes + 1, font, shape, maxwords))
            db.commit()
        else:
            cur.execute('insert into photostyle(ProjectID,times,font,shape,maxwords) values(%s,%s,%s,%s,%s)',
                        (ProjectID, 0, font, shape, maxwords))
            db.commit()
        return render_template('AnalyseResult.html', wordcloudStream=wordcloudStream, Asummary=Asummary,
                               wordcloud=str(ProjectID) + ".jpg", highwords=str(ProjectID) + '.txt',
                               summary=str(ProjectID) + '.txt')


# 定义我的信息页面
@app.route('/myinfo/', methods=['GET', 'POST'])
def myinfo():
    if request.method == "GET":
        UserEmail = session["UserEmail"]
        cur.execute("select UserName from userinfo where UserEmail = %s ", (UserEmail))
        username = cur.fetchone()[0]
        print(username)
        UserPassword = session["UserPassWord"]
        return render_template('myinfo.html', UserEmail=UserEmail, username=username, UserPassword=UserPassword)
    else:
        UserId = session["UserId"]
        UserName = str(request.form.get('UserName'))
        UserEmail = str(request.form.get('UserEmail'))
        UserPassWord1 = str(request.form.get('UserPassWord1'))
        UserPassWord2 = str(request.form.get('UserPassWord2'))
        print(UserName, UserEmail, UserPassWord1)
        if UserPassWord1 == UserPassWord2:
            cur.execute(
                'UPDATE userinfo SET UserName=%s, UserEmail=%s,UserPassword=%s where UserId = %s',
                (UserName, UserEmail, UserPassWord1, UserId))
            db.commit()
            session["UserEmail"] = UserEmail
            session["UserPassWord"] = UserPassWord1
            flag = '更新成功'
            return render_template('myinfo.html', UserEmail=UserEmail, username=UserName, flag=flag,
                                   UserPassword=UserPassWord1)
        else:
            flag = '两次密码不一致，更新失败'
            UserPassWord = session['UserPassword']
            return render_template('myinfo.html', UserEmail=UserEmail, username=UserName, UserPassWord=UserPassWord,
                                   flag=flag)


@app.route('/download1/<filename>')
def download1(filename):
    base_path = os.path.abspath(os.path.dirname(__file__))
    download_path = base_path + '/static/wordcloud/'
    print(filename)
    print(type(filename))
    filename = filename.encode('utf-8').decode('utf-8')
    response = make_response(send_from_directory(download_path, filename))
    response.headers["Content-Disposition"] = "attachment; filename" + filename
    return response


@app.route('/download2/<filename>')
def download2(filename):
    base_path = os.path.abspath(os.path.dirname(__file__))
    download_path = base_path + '/static/highwords/'
    print(filename)
    print(type(filename))
    filename = filename.encode('utf-8').decode('utf-8')
    response = make_response(send_from_directory(download_path, filename))
    response.headers["Content-Disposition"] = "attachment; filename" + filename
    return response


@app.route('/download3/<filename>')
def download3(filename):
    base_path = os.path.abspath(os.path.dirname(__file__))
    download_path = base_path + '/static/summary/'
    print(filename)
    print(type(filename))
    filename = filename.encode('utf-8').decode('utf-8')
    response = make_response(send_from_directory(download_path, filename))
    response.headers["Content-Disposition"] = "attachment; filename" + filename
    return response


@app.route('/jump/<ProjectID>')
def jumap(ProjectID):
    print(ProjectID)
    base_path = os.path.abspath(os.path.dirname(__file__))
    cur.execute("select * from analysisresult where projectID = %s", (ProjectID))
    project = cur.fetchone()
    wordcloudStream = return_img_stream(base_path + project[2])
    with open(base_path + project[4], 'rb') as f:
        Asummary = f.read()
    with open(base_path + project[2], 'rb') as f:
        AnalyseText = f.read()
    if len(AnalyseText) != 0:
        session["AnalyseText"] = AnalyseText.decode('utf-8')
    session["ProjectID"] = ProjectID
    session["Asummary"] = Asummary
    session["summaryfilepath"] = base_path + project[4]

    maxwords = 200
    wt = keywords.keyword(AnalyseText, maxwords, ProjectID)
    highwordsfilePath = wt[1]
    session["highwordsfilePath"] = highwordsfilePath
    session["wt0"] = wt[0]

    return render_template('AnalyseResult.html', wordcloudStream=wordcloudStream, Asummary=Asummary,
                           wordcloud=str(ProjectID) + ".jpg", highwords=str(ProjectID) + '.txt',
                           summary=str(ProjectID) + '.txt')


@app.route('/changePassword/', methods=['GET', 'POST'])
def changePassword():
    if request.method == "GET":
        return render_template('password.html')
    else:
        print("运行到这里了")
        data = request.get_data()
        print(data)
        data = json.loads(data)
        UserEmail = data['email']
        user = cur.execute("select * from userinfo where UserEmail = %s", (UserEmail))
        if user:
            UserPassword = data['password']
            print(UserEmail, UserPassword)
            cur.execute(
                'UPDATE userinfo SET UserPassword=%s where UserEmail= %s',
                (UserPassword, UserEmail))
            db.commit()
            return json.dumps({'msg': 'success'})
        else:
            return json.dumps({'msg': '邮箱错误，请查证后再次填写'})


@app.route('/sendCode/', methods=['POST'])
def sendCode():
    data = request.get_data()
    print(data)
    data = json.loads(data)
    UserEmail = data['email']
    code = random.randint(1000, 10000)
    try:
        sendEmail(UserEmail, code)
        session['code'] = code
        msg = {'msg': 'success'}
        return json.dumps(msg)
    except:
        msg = {'msg': '邮箱错误，请查证后再发送'}
        return json.dumps(msg)


@app.route('/verify/', methods=['POST'])
def verify():
    data = request.get_data()
    data = json.loads(data)
    verity_code = data['verity_code']
    if int(verity_code) == session['code']:
        msg = {'msg': 'success'}
        return json.dumps(msg)

    else:
        msg = {'msg': '请填写正确的验证码'}
        return json.dumps(msg)


if __name__ == '__main__':
    app.run(host="localhost", port=5000)
